package com.lecture.java8.excel.dyr.d;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Test {
    public static void main(String[] args) {
        String excelFilePath = "D:\\study\\tmp\\0611\\1大学生人数.xls";

        try {

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static List<Map<String, Object>> readExcel(String excelFilePath) throws IOException, InvalidFormatException {
        List<Map<String, Object>> excelData = new ArrayList<>();

        FileInputStream inputStream = new FileInputStream(excelFilePath);
        Workbook workbook = WorkbookFactory.create(inputStream);

        Sheet sheet = workbook.getSheetAt(0); // 假设你想要读取第一个工作表

        Row headerRow = sheet.getRow(0);
        int rowCount = sheet.getPhysicalNumberOfRows();

        for (int rowIndex = 1; rowIndex < rowCount; rowIndex++) {
            Row currentRow = sheet.getRow(rowIndex);
            Map<String, Object> rowMap = new HashMap<>();

            for (int cellIndex = 0; cellIndex < headerRow.getLastCellNum(); cellIndex++) {
                Cell currentCell = currentRow.getCell(cellIndex);
                CellType cellType = CellType.forInt(currentCell.getCellType());

                String columnName = headerRow.getCell(cellIndex).getStringCellValue();

                switch (cellType) {
                    case STRING:
                        rowMap.put(columnName, currentCell.getStringCellValue());
                        break;
                    case NUMERIC:
                        rowMap.put(columnName, currentCell.getNumericCellValue());
                        break;
                    case BOOLEAN:
                        rowMap.put(columnName, currentCell.getBooleanCellValue());
                        break;
                    case BLANK:
                        rowMap.put(columnName, ""); // 如果是空白单元格，以空字符串表示
                        break;
                    default:
                        // 对于其他类型的单元格，你可以根据需要进行处理
                        rowMap.put(columnName, "");
                }
            }
            excelData.add(rowMap);
        }

        workbook.close();
        inputStream.close();

        return excelData;
    }
}
